#include "stdafx.h"
#include "ISProto.h"
#include "is_protocol.pb.h"
#include "gshandler.h"
#include "svrhandlermgr.h"
#include "svr_protheader.h"
#include "rolemgr.h"

#ifdef _WIN32
#pragma comment(lib, "Ws2_32.lib")
#endif 

IMPLEMENT_SINGLETON(CGSHandler)

CGSHandler::CGSHandler(void)
{
    //m_oProto.Init();
}

CGSHandler::~CGSHandler(void)
{

}

void CGSHandler::ProcessPacket(UINT32 dwSvrID, const char * pszBuf, UINT32 dwBufLen)
{
    const SSvrMsgHeader* pstHeader = reinterpret_cast<SSvrMsgHeader*>(const_cast<char *>(pszBuf));
    UINT16 wMsgID = ntohs(pstHeader->wMsgID);
    UINT32 dwTransID = ntohl(pstHeader->dwTransID); 

    char* pBodyData = const_cast<char*>(pszBuf + sizeof(SSvrMsgHeader));
    INT32 nBodyLen = dwBufLen - sizeof(SSvrMsgHeader);

    ::google::protobuf::Message * pMsg = m_oProto.Decode(wMsgID, pBodyData, nBodyLen);

    if (pMsg == NULL)
        return;

    //DBG_INFO("%d---%d", dwSvrID, wMsgID);
    switch (wMsgID)
    {
    case GIID_ENTER_REQ:
        _OnProcessEnter(dwSvrID, dwTransID, (GIPKG_ENTER_REQ *)pMsg);
        break;
    case GIID_LEAVE_REQ:
        _OnProcessLeave(dwSvrID, dwTransID, (GIPKG_LEAVE_REQ *)pMsg);
        break;
    default:
        _OnProceRoleMsg(dwSvrID, dwTransID, wMsgID, pMsg);
        break;
    }
}



bool CGSHandler::Send(UINT32 dwSvrID, UINT32 dwTransID, int nMsgID, ::google::protobuf::Message * pMsg)
{
    char pBuf[MAX_PACKET_LEN] = {0};

    SSvrMsgHeader * stHeader = (SSvrMsgHeader *)pBuf;
    stHeader->wMsgID = htons(nMsgID);
    stHeader->dwTransID = htonl(dwTransID);

    char* pBodyData = pBuf + sizeof(SSvrMsgHeader);

    int nTotolSize = pMsg->ByteSize() + sizeof(SSvrMsgHeader);
    bool bFlag = pMsg->SerializeToArray(pBodyData, sizeof(pBuf) - sizeof(SSvrMsgHeader));
    if (!bFlag)
        return false;

    return CSvrHandlerMgr::Instance()->GetBaseSvrMgr()->Send(dwSvrID, pBuf, nTotolSize);
}

bool CGSHandler::Run(void)
{
    CRoleMgr::Instance()->Process();
    return true;
}


void CGSHandler::OnConnected(UINT32 dwSvrID)
{
    CRoleMgr::Instance()->SessionConnected();
}

void CGSHandler::OnDisConnected(UINT32 dwSvrID, INT32 nErrCode)
{
    CRoleMgr::Instance()->SessionDisConnected(dwSvrID);
}


void CGSHandler::_OnProcessEnter(UINT32 dwSvrID, UINT32 dwTransID, GIPKG_ENTER_REQ *pEnterReq)
{
    CRoleMgr::Instance()->RoleEnter(dwSvrID, dwTransID, pEnterReq);
}

void CGSHandler::_OnProcessLeave(UINT32 dwSvrID, UINT32 dwTransID, GIPKG_LEAVE_REQ * pLeaveReq)
{
    CRoleMgr::Instance()->RoleLeave(dwSvrID, dwTransID, pLeaveReq);
}


void CGSHandler::_OnProceRoleMsg(UINT32 dwSvrID, UINT32 dwTransID, UINT16 wMsgID, ::google::protobuf::Message * pMsg)
{
    CRoleMgr::Instance()->ProceRoleMsg(dwSvrID, dwTransID, wMsgID, pMsg);
}
